/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Engine2D.network;

import Engine2D.network.MulticastListener.Server;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Garys
 */
public class MulticastController {

    private ArrayList<MulticastListener> listeners = new ArrayList<MulticastListener>();
    private ArrayList<MulticastBroadcaster> broadcasters = new ArrayList<MulticastBroadcaster>();

    public MulticastController() {
    }

    public void startBroadcasting(String serverName, String serverAddress, int serverPort, String bcAddress, int startPort, int endPort) throws IOException {

        for (int i = startPort; i <= endPort; i++) {
            try {
                MulticastBroadcaster broadcaster = new MulticastBroadcaster(serverName, serverAddress, serverPort, bcAddress, i);
                broadcaster.start();
                broadcasters.add(broadcaster);
            } catch (Exception e) {
                System.out.println("Port: "+i+" is unavailable for broadcasting.");
            }

        }
    }

    public void startListening(String address, int startPort, int endPort) throws IOException {
        for (int i = startPort; i <= endPort; i++) {
            try {
                MulticastListener listner = new MulticastListener(address, i);
                listner.start();
                listeners.add(listner);
            } catch (Exception e) {
                System.out.println("Port: "+i+" is unavailable for listening.");
            }

        }
    }

    public ArrayList<Server> getServers() {

        ArrayList<Server> servers = new ArrayList<Server>();
        for (MulticastListener multicastListener : listeners) {
            servers.addAll(multicastListener.getServers());
        }

        return servers;
    }

    public static void main(String[] args) throws IOException {

        MulticastController controller = new MulticastController();
        controller.startBroadcasting("hello", "192.168.1.0", 8000, "230.0.0.1", 2000, 3000);
        controller.startListening("230.0.0.1", 2000, 3000);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(MulticastController.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println(controller.getServers().size());



    }
}
